<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use think\Db;
use think\Cache;
use think\Cookie;
use think\Config;

use app\common\model\Organ as OrganModel;
use app\common\model\Examination as ExaminationModel;
use app\common\model\ExaminationResult as ExaminationResultModel;
use app\common\model\DefaultTemplate as DefaultTemplateModel;
use think\Request;
use think\Session;

class Index extends IndexBase{
    protected $organ_model, $examination_model, $isweixin, $wdata, $examination_result_model;

    protected function _initialize(){
        parent::_initialize();
        header("Content-type:text/html;charset=utf-8");
        $usercode = Session::get('usercode');
        $res      = Db::name('user')->where('usercode', $usercode)->find();
        if(empty($usercode) && !$res){ //login
            $this->login();
        }
    }

    /**
     * 获取世界杯数据
     */
    public function getData(Request $request){
        $name = $request->post('name');
        if($name == 'sjb'){
            $teams = Db::name('teamvs')->select();
            $teams = $this->convert_arr_key($teams, 'id');
            return json(array('info' => $teams, 'status' => 1, 'len' => count($teams)));
        }else{
            echo "<script>window.history.go(-1);</script>";
            exit(0);
        }
    }

    /**
     * 指定的 id 作为数组的键名
     */
    public function convert_arr_key($arr, $key_name){
        $result = array();
        foreach($arr as $key => $val){
            $result[$val[$key_name]] = $val;
        }
        return $result;
    }

    /**
     *世界杯获取用户选择数据
     */
    public function receiveData(Request $request){
        $dayTime     = date('YmdHis', time()); //当钱时间
        $daySixtime  = strtotime(date("Y-m-d 06:00:00"));  //当天6点
        $dayNinetime = strtotime(date("Y-m-d 21:00:00"));  //当天21点

        $dayTentime  = date("Y-m-d 22:00:00");  //当天十点
        $nextdaytime = date("Y-m-d 02:00:00", strtotime("+1 day"));//第二天2点
        //$dayTentime =strtotime($dayTentime);

        $userResult = $request->post();
        if(empty($userResult['result'])){
            exit("<script>alert('请选择球队!');window.history.go(-1);</script>");
        }

        $usercode      = $request->session('usercode');
        $country       = $userResult['result'];
        $competitionId = $userResult['id']; //赛事Id

        //用户当前时间在6：00-21：00可以投票
        $now = time();
        if($now <= $dayNinetime && $now >= $daySixtime){
            $competitionInfo = Db::name('teamvs')->where('id', $competitionId)->find();
            $competitionTime = strtotime($competitionInfo['start_time']);
            //p($competitionInfo);
            if($competitionTime >= $now){ //赛事时间>当前时间 投票
                //用户一天只能投票2次
                $day = date('Ymd', $now);
                //同一场赛事头一次
                $result = Db::name('record')->where('competitionId', $competitionId)->where('usercode', $usercode)->find();
                if($result){
                    return json(array('status' => 0, 'msg' => '同一场赛事只能投一次!'));
                }
                //插入用户投票记录表
                $data = array(
                    'usercode'      => $usercode,
                    'time'          => $now,
                    'formattime'    => $dayTime,
                    'team'          => $country,
                    'competitionId' => $competitionId,
                    'day'           => date('Ymd', $now)
                );
                $res  = Db::name('record')->insert($data);
                if(!$res){
                    return json(array('status' => 0, 'msg' => '请不要频繁提交!'));
                }else{
                    $data = array(
                        'endtime'    => time(),
                        'formattime' => date('Y-m-d H:i:s', time())
                    );
                    //修改用户信息
                    Db::name('user')->where('usercode', $usercode)->update($data);//->inc('points')
                    return json(array('status' => 1));
                }
            }else{
                return json(array('status' => 0, 'msg' => '亲，该赛事已过期!'));
            }
        }else{//不再投票时间
            return json(array('status' => 0, 'msg' => '不在投票时间!'));
        }
    }

    /**
     *世界杯进入首页开始
     */
    public function index(Request $request){
        $sesssion_user_code = $request->session('usercode');
        $res                = Db::name('user')->where('usercode', $sesssion_user_code)->find();
        if(!empty($sesssion_user_code) && $res){ //进入竞猜
            return $this->fetch('sjb');
        }else{ //login
            $this->redirect('index/Index/login');
        }
    }

    /**
     * 登陆
     */
    public function login(){
        return $this->fetch('login');
    }

    /**
     * 登录处理
     */
    public function dealLogin(Request $request){
        $userCode = trim($request->post('usercode'));
        if(empty($userCode)){
            exit("<script>alert('请输入标识码!');window.history.go(-1);</script>");
        }
        $res = Db::name('user')->where('usercode', $userCode)->find();
        if($res){
            Session::set('usercode', $userCode);
            $this->redirect('index/Index/index');
        }else{
            exit("<script>alert('非法用户!');window.history.go(-1);</script>");
        }
    }
}